package org.jeecg.modules.charge.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.sms.SmsUtil;
import org.jeecg.entity.charge.ChargeBills;
import org.jeecg.modules.charge.entity.ChargePringArea;
import org.jeecg.modules.charge.service.impl.ChargeBillsServiceImpl;
import org.jeecg.modules.message.entity.SysMessage;
import org.jeecg.modules.system.entity.SmsEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
* @Description: 催缴单打印
* @Author: jeecg-boot
* @Date:   2019-12-10
* @Version: V1.0
*/
@Slf4j
@Api(tags="催缴单打印")
@RestController
@RequestMapping("/b/charge/print")
public class ChargePrintAreaController {

    @Autowired
    private ChargeBillsServiceImpl chargeBillsService;

    private static String  templateCode ="SMS_158942668";

    /**
     * 催缴账单查询
     * @param chargeBills
     * @param req
     * @return
     */
    @PostMapping(value = "/getPromptList")
    public Result<IPage<ChargeBills>> getPromptList(@RequestBody  ChargeBills chargeBills,
                                                    HttpServletRequest req) {
        Result<IPage<ChargeBills>> result = new Result<IPage<ChargeBills>>();
        if(chargeBills.getPageNo() == 0){
            chargeBills.setPageNo(1);
        }
        if(chargeBills.getPageSize() == 0){
            chargeBills.setPageSize(10);
        }
        try {
            Page<ChargeBills> page = new Page<ChargeBills>(chargeBills.getPageNo(), chargeBills.getPageSize());
            page.setRecords(chargeBillsService.getPageBillsList(page,chargeBills));
            result.setSuccess(true);
            result.setResult(page);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 打印账单进行合并
     * @param chargeBills
     * @param req
     * @return
     */
    @PostMapping(value = "/printArea")
    public Result<List<ChargeBills>> printArea(@RequestBody ChargeBills chargeBills,
                                                   HttpServletRequest req) {
        Result<List<ChargeBills>> result = new Result<List<ChargeBills>>();
        try {
            List<ChargeBills> list = new ArrayList<ChargeBills>();
            List<ChargeBills> billsList = new ArrayList<ChargeBills>();
            if(StringUtils.isNotEmpty(chargeBills.getCustomerId()) || StringUtils.isNotEmpty(chargeBills.getRentId())){
                list = chargeBillsService.getBillsList(chargeBills);
            }
            if(list != null && list.size() > 0){
                    for(ChargeBills bill:list){
                        bill.setNum(1);
                        boolean flag = false;
                        String cny = bill.getZjCny().replaceAll("-", "/");
                        for(ChargeBills bills:billsList){
                            if (bill.getFeeitemId().equals(bills.getFeeitemId())
                                    && bill.getDue().compareTo(bills.getDue()) == 0) {//判断收费项目以及金额
                                     cny += "," + bills.getZjCny().replaceAll("-", "/");
                                     bills.setNum(bills.getNum() + 1);
                                     bills.setZjCny(cny);
                                     flag = true;
                            }
                        }
                        if (!flag) {
                            billsList.add(bill);
                        }
                    }
                for (ChargeBills util : billsList) {
                    String[] zjCny = util.getZjCny().split(",");
                    StringUtils.buffSort(zjCny);
                    util.setDue(util.getDue().multiply(new BigDecimal(util.getNum())).setScale(2,BigDecimal.ROUND_HALF_UP));
                    if (zjCny.length > 1) {
                        switch(zjCny.length){
                            case 1:
                                util.setZjCny(zjCny[zjCny.length - 1]);
                                break;
                            default:
                                util.setZjCny(zjCny[0]+"-"+zjCny[zjCny.length - 1]);
                                break;
                        }
                    }
                }
            }
            result.setSuccess(true);
            result.setResult(billsList);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 打印账单进行合并
     * @param chargeBills
     * @param req
     * @return
     */
    @PostMapping(value = "/printAreaAll")
    public Result<List<ChargePringArea>> printAreaAll(@RequestBody ChargeBills chargeBills,
                                               HttpServletRequest req) {
        Result<List<ChargePringArea>> result = new Result<List<ChargePringArea>>();
        try {
            List<ChargePringArea> areaList = chargeBillsService.getChargePingArea(chargeBills);
            result.setSuccess(true);
            result.setResult(areaList);
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 短信通知
     * @param chargeBills
     * @param req
     * @return
     */
    @PostMapping(value = "/sendSmsChargeBills")
    public Result<String> sendSmsChargeBills(@RequestBody ChargeBills chargeBills,
                                                      HttpServletRequest req) {
        Result<String> result = new Result<String>();
        try {
              List<ChargePringArea> areaList = chargeBillsService.getChargePingArea(chargeBills);
            for(ChargePringArea area:areaList){
                SmsEntity smsEntity = SmsUtil.sendSms(area.getRenPhone(), templateCode, "community", area.getProjectName());
                String status = "";
                if (smsEntity.getMessage().equalsIgnoreCase("OK")){
                    status = "1";
                }else {
                    status = "2";
                }
                saveMessage(smsEntity.getContent(),area.getProjectName(),area.getCusPhone(),area.getRenPhone(),status);
            }
              result.setSuccess(true);
              result.setResult("请选择需要通知的业主或租户！");
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }




    /**
       * @param excelName
       * double计算保留两位小数
       * @return
       * @throws IOException
       */
    private Double getBigDecimal(Double sum){
        BigDecimal bigsum = new BigDecimal(sum);
        Double sums = bigsum.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return sums;
    }

    private void saveMessage(String content,String projectId,String depatrId,String phone,String status){
        SysMessage sysMessage = new SysMessage();
        sysMessage.setEsType("1");
        sysMessage.setEsContent(content);
        sysMessage.setProjectId(projectId);
        sysMessage.setDepartId(depatrId);
        sysMessage.setEsReceiver(phone);
        sysMessage.setEsTitle("物业费短信");
        sysMessage.setEsSendStatus(status);
        sysMessage.setEsSendTime(new Date());
    }
}
